package com.usian.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.usian.handler.GlobalBlockHandler;
import com.usian.feign.UserFeign;
import com.usian.handler.GlobalFallback;
import com.usian.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.Date;

@RestController
public class ConsumerController {
    //简化了发起 HTTP 请求以及处理响应的过程，并且支持 REST
    @Autowired
    private RestTemplate restTemplate; //远程调用的模板
    @Autowired
    private LoadBalancerClient loadBalancerClient; //从注册中心取参数
    @Autowired
    private UserFeign userFeign;

    @GetMapping("getUserById/{id}")
    @SentinelResource(value = "getUserById",
                      blockHandlerClass = {GlobalBlockHandler.class},
                      blockHandler = "blockHandlerMethod",
                      fallbackClass = GlobalFallback.class,
                      fallback = "fallbackMethod")
    public User getUserById(@PathVariable Integer id) {
       /* ServiceInstance si = loadBalancerClient.choose("nacos-provider");//通过名字取到一个服务实例
        String host = si.getHost();
        int port = si.getPort();

        String url = "http://" + host + ":" + port + "/getUserById/" + id;
        System.out.println(url);
        //通过远程调用服务提供方的接口来获取一个user对象
        User user = restTemplate.getForObject(url, User.class);
        return user;*/

        //通过feign声明式服务调用
        System.out.println(Thread.currentThread().getName() + "-----" + new Date());
        return userFeign.getUserById(id);
    }

    @RequestMapping("addUser")
    public int addUser() {
        User user = new User();
        user.setId(1);
        return userFeign.addUser(user);
    }

    @RequestMapping("delUser")
    public int delUser(Integer id) {
        return userFeign.delUser(id);
    }
}
